package me.zhengjie.utils.enums;
import javax.persistence.AttributeConverter;

public abstract class AbstractEnumConverter<ATTR extends Enum<ATTR> & PersisEnum<E>, E> implements AttributeConverter<ATTR, E> {

    private final Class<ATTR> clazz;

    public AbstractEnumConverter(Class<ATTR> clazz) {
        this.clazz = clazz;
    }

    @Override
    public E convertToDatabaseColumn(ATTR attribute) {
        return attribute != null ? attribute.getData() : null;
    }

    @Override
    public ATTR convertToEntityAttribute(E code) {
        if (code == null) return null;

        ATTR[] enums = clazz.getEnumConstants();

        for (ATTR e : enums) {
            if (e.getData().equals(code)) {
                return e;
            }
        }

        throw new UnsupportedOperationException("枚举转化异常。枚举【" + clazz.getSimpleName() + "】,数据库库中的值为：【" + code + "】");
    }
}
